#pragma once 
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace LogModule;
const std::string defaultdict = "./dictionary.txt";
const std::string sep = ": ";
class Dict {
public: 
    Dict(const std::string& path = defaultdict) : _dict_path(path) {}
    bool LoadDict() {
        std::ifstream in(_dict_path);
        if(!in.is_open()) {
            LOG(LogLevel::DEBUG) << "打开字典：" << _dict_path << "出错了。";
            return false;
        }
        std::string line;
        while (std::getline(in, line)) {
            auto index = line.find(sep);
            if(index == std::string::npos) {
                LOG(LogLevel::WARNING) << "解析：" << line << "失败了";
                continue;
            }
            std::string english = line.substr(0, index);
            std::string chinese = line.substr(index + sep.size()); // 别忘了加上分割符
            if(english.empty() || chinese.empty()) {
                LOG(LogLevel::WARNING) << "没有有效内容：" << line;
                continue;
            }
            _dict.insert(std::make_pair(english, chinese));
            LOG(LogLevel::DEBUG) << "加载到了：" << line;
        }
        return true;
    }
    std::string Translate(const std::string& word, InetAddr& client) {
        auto it = _dict.find(word);
        if(it == _dict.end()) {
            LOG(LogLevel::DEBUG) << "进入到了翻译的模块，[" << client.Ip() << " : " << client.Port() << "]# " << word << "->none";
            return "none";
        }else {
            LOG(LogLevel::DEBUG) << "进入到了翻译的模块，[" << client.Ip() << " : " << client.Port() << "]# " << word << "->" << it->second;
            return it->second;
        }
    }
    ~Dict() {}
private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
};